<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/10/6
 * Time: 09:23
 */

namespace app\api\service;


use app\api\model\MessageTemplate;
use think\Cache;
use think\Exception;


class WxMessage
{
    //小程序消息推送属性
    private $sendUrl = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?" .
    "access_token=%s";
    //不让子类控制颜色
    private $color = 'black';
    protected $tplID;
    protected $page;
    protected $formID;
    protected $data;
    protected $emphasisKeyWord;



     function __construct($t_id,$title)
    {
        if (!Cache::has($t_id.'mini')){
            $mini = \app\api\model\Mini::getMiniByUser($t_id);
        }else{
            $mini = Cache::get($t_id.'mini');
        }
        $token = $this->getAcessTokenValue($mini['authorizer_appid']);
        $this->sendUrl = sprintf($this->sendUrl,$token);
        $template = MessageTemplate::getTemplate($t_id,$title);
        $this->tplID = $template->template_id;
    }

    /**
     * 小程序信息推送
     * @param $openID
     * @return bool
     * @throws Exception
     */
    protected function sendMessage($openID){
        $data = [
            'touser' => $openID,
            'template_id' => $this->tplID,
            'page' => $this->page,
            'form_id' => $this->formID,
            'data' => $this->data,
            //'color' => $this->color,
            'emphasis_keyword' => $this->emphasisKeyWord
        ];
        $result = curl_post( $this->sendUrl,$data);
        $result =json_decode($result,true);
        if ($result['errcode'] == 0){
            return true;
        }else{
           return false;
        }
    }

    /**
     * 获取AccessToken
     * @param $appid
     * @return bool|mixed
     */
    private function getAcessTokenValue($appid){
        if (cache($appid)){
            $access_token = json_decode(cache($appid));
        }else{
            $mini = new Mini();
            $access_token =  $mini->getAccessToken($appid);
        }
        return $access_token;
    }
}